package com.zyz.I_多线程.创建方式.练习.进阶;

/**
 * @author: vick
 * @Date: 2025/3/21
 * @Description:
 * @version: 1.0
 */
public class Race implements Runnable{
    //胜利者
    private static String winner;

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        for (int i = 1; i <= 100; i++) {
            if (name.equals("兔子") && i%20 == 0) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            boolean flag = gameOver(i);
            if (flag) {
                break;
            }
            System.out.println(name + "跑了" + i + "米");
        }
    }

    //判断比赛有没有完成
    public boolean gameOver(int step) {
        //胜利者出现了，那就结束
        if (winner != null) {
            return true;
        }
        if (step >= 100) {
            winner = Thread.currentThread().getName();
            System.out.println("胜利者是：" + winner);
            return true;
        }
        return false;
    }
}
